<?php
session_start();
if(isset($_SESSION['user']))
	header('location: index.php');

?>
<html>
<head>
<title>ShareCon - Login</title>
</head>
<body>

<div id="main" style="padding-left:15%; padding-right:15%">
<div id="inner" style="border: 2px solid black; padding:5%;">

<div id='loginset'>
<br>
<h1>Login</h1>

<form id='loginforms' method="post" action="login.php">
<table border = 0>
<tr>
	<td>Username:</td>
	<td><input type="text" name="user" /></td>
</tr>
<tr>
	<td>Password:</td>
	<td><input type="password" name="passwd" /></td>
</tr>
<tr>
	<td></td>
	<td><input type="submit" value="Login" style="float:right" /></td>
</td>
</table>
</form>

<?php
if (isset($_POST['user']) && $_POST['passwd']) {
	$user = trim($_POST['user']);
	$passwd = trim($_POST['passwd']);
	$digest = md5($passwd);

	$con = mysqli_connect("localhost", "root", NULL, "csproj2");
	if (mysqli_connect_errno()) {
		printf("Connect failed: %s", mysqli_connect_error());
		exit();
	}

	$stmt = $con->prepare("SELECT p_id FROM person WHERE p_id = ? AND password = ?");


	$stmt->bind_param('ss', $user, $digest);
	$stmt->execute();

	$stmt->bind_result($pid);
	$stmt->fetch();
	//exact match
	if ($user == $pid) {

		$pid = htmlspecialchars($pid);
		$_SESSION['user'] = $pid;
		header('location: index.php');
	} else {
		printf("<span style='color:red'>Bad username or password.</span><br><br>");
	}

	$stmt->close();
	$con->close();
}

?>


<span>New? <a href="/register.php">Register here!</a></span><br>
<span>Return to the <a href="/index.php">home page.</a></span>
</div>
</div></div>

</body></html>

